package com.yjs.app.trade.core.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import net.sf.json.JSONObject;

public class MongoUtil {

	private static String ip = "";
	
	private static int port = 0;
	
	private static MongoClient mongoClient = null;
	
	private static MongoDatabase mongoDataBase = null;
	
	private static Logger log = LoggerFactory.getLogger(Logger.class);
	
	/*static {
		if (mongoClient == null && mongoDataBase == null) {
			ip = PropertiesUtils.getProperty("mongodb.url");
			port = Integer.parseInt(PropertiesUtils.getProperty("mongodb.port"));
			mongoClient = new MongoClient(ip, port);
			mongoDataBase = mongoClient.getDatabase(PropertiesUtils.getProperty("mongodb.database"));
		}
	}*/
	
	/**
	 * 获取列表数据
	 * @param type 集合名称
	 * @param map 搜索条件 
	 * @param projection 过滤条件
	 * @param pageNo 页数
	 * @param pageSize 分页大小
	 * @param sorts 排序
	 * @return
	 */
	public static List<String> getListInfo (String type, Map<String,Object> map, List<String> projection,Integer pageNo, Integer pageSize, Map<String, Integer> sorts) {
		MongoCollection<Document> collection = mongoDataBase.getCollection(type);
		BasicDBObject cond = new BasicDBObject();
		BasicDBList condList = new BasicDBList();
		BasicDBObject exclude = new BasicDBObject().append("_id", 0);
		Document document = new Document();
		if (map != null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (StringUtils.equals("$or", entry.getKey())) {
					cond.put("$or", entry.getValue());
				} else {
					condList.add(new BasicDBObject(entry.getKey(), entry.getValue()));
				}
			}
			if (condList != null && condList.size() > 0) {
				cond.put("$and", condList);
			}
		}
		if (projection != null && projection.size() > 0) {
			for (String string : projection) {
				exclude.append(string, 0);
			}
		}
		if (sorts != null) {
			for (Map.Entry<String, Integer> entry : sorts.entrySet()) {
				document.append(entry.getKey(), entry.getValue());
			}
		}
		FindIterable<Document> findIterable = null;
		if (pageNo != null && pageSize != null) {
			findIterable = collection.find(cond).projection(exclude).skip((pageNo - 1) * pageSize).limit(pageSize).sort(document);
		} else {
			findIterable = collection.find(cond).projection(exclude).sort(document);
		}
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		List<String> list = new ArrayList<>();
		while (mongoCursor.hasNext()) {
			list.add(mongoCursor.next().toJson());
		}
		List<String> values = new ArrayList<>();
		for (String string : list) {
			@SuppressWarnings("unchecked")
			Map<String, Object> jsonMap = (Map<String, Object>) JSON.parse(string);
			for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
				if (entry.getValue().toString().indexOf("{") != -1 && 
						entry.getValue().toString().indexOf("}") != -1) {
					try {
						if (entry.getValue().toString().indexOf("numberLong") != -1 &&
								JSONObject.fromObject(entry.getValue()).get("$numberLong") != null) {
							jsonMap.put(entry.getKey(), JSONObject.fromObject(entry.getValue()).getInt("$numberLong"));
						}
					} catch (Exception e) {
						log.error("mongoDB查询出现其他数据格式~~~~~~" + e);
					}
				}
			}
			values.add(JSONObject.fromObject(jsonMap).toString());
		}
		return values;
	}
	
	/**
	 * 获取单条数据
	 * @param type
	 * @param userNumber
	 * @param map
	 * @return
	 */
	public static String getOneInfo (String type, Map<String,Object> map, List<String> projection) {
		MongoCollection<Document> collection = mongoDataBase.getCollection(type);
		BasicDBObject exclude = new BasicDBObject().append("_id", 0);
		BasicDBObject cond = new BasicDBObject();
		BasicDBList condList = new BasicDBList();
		if (map != null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				BasicDBObject value = new BasicDBObject();
				value.append(entry.getKey(), entry.getValue());
				condList.add(value);
			}
		}
		cond.put("$and", condList);
		if (projection != null && projection.size() > 0) {
			for (String string : projection) {
				exclude.append(string, 0);
			}
		}
		FindIterable<Document> findIterable = collection.find(cond).projection(exclude);
		if (findIterable.first() != null) {
			return findIterable.first().toJson();
		}
		return "";
	}
	
	/**
	 * @param member 查询memberId类型
	 * @param memberId 会员ID
	 * @param projections 过滤条件
	 * @param sort 排序
	 * @return
	 */
	public static List<String> composeNormalParam (String seachName, String memberId, String projections, String sort, Integer sortType, String collectionName, Integer pageNo, Integer pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(seachName, memberId);
		List<String> projection = new ArrayList<String>();
		if (projections != null) {
			projection.add(projections);
		}
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		if (sort != null && sortType != null) {
			sorts.put(sort, sortType);
		}
		return getListInfo(collectionName, map, projection, pageNo, pageSize, sorts);
	}
	
	/**
	 * @param member 查询memberId类型
	 * @param memberId 会员ID
	 * @param projections 过滤条件
	 * @param sort 排序
	 * @return
	 */
	public static String composeNormalById (String seachName, String memberId, String projections, String collectionName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(seachName, memberId);
		List<String> projection = new ArrayList<String>();
		if (projections != null) {
			projection.add(projections);
		}
		return getOneInfo(collectionName, map, projection);
	}
	
	/**
	 * @param member 查询memberId类型
	 * @param memberId 会员ID
	 * @param projections 过滤条件
	 * @param sort 排序
	 * @return
	 */
	public static String composeNormalById (Map<String, Object> map, String projections, String collectionName) {
		List<String> projection = new ArrayList<String>();
		if (projections != null) {
			projection.add(projections);
		}
		return getOneInfo(collectionName, map, projection);
	}
	
	public static List<String> getOtherMongoList(String ip, int port, String database, String collectionName, Map<String, Object> searchMap, Map<String, Integer> sortMap) {
		MongoClient mongoClient = new MongoClient(ip, port);
		MongoDatabase mongoDataBase = mongoClient.getDatabase(database);
		MongoCollection<Document> collection = mongoDataBase.getCollection(collectionName);
		
		BasicDBObject cond = new BasicDBObject();
		BasicDBList condList = new BasicDBList();
		BasicDBObject exclude = new BasicDBObject().append("_id", 0);
		Document document = new Document();
		if (searchMap != null) {
			for (Map.Entry<String, Object> entry : searchMap.entrySet()) {
				BasicDBObject value = new BasicDBObject();
				value.append(entry.getKey(), entry.getValue());
				condList.add(value);
			}
		}
		cond.put("$and", condList);
		if (sortMap != null) {
			for (Map.Entry<String, Integer> entry : sortMap.entrySet()) {
				document.append(entry.getKey(), entry.getValue());
			}
		}
		FindIterable<Document> findIterable = null;
		findIterable = collection.find(cond).projection(exclude).sort(document);
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		List<String> list = new ArrayList<>();
		while (mongoCursor.hasNext()) {
			list.add(mongoCursor.next().toJson());
		}
		List<String> values = new ArrayList<>();
		for (String string : list) {
			@SuppressWarnings("unchecked")
			Map<String, Object> jsonMap = (Map<String, Object>) JSON.parse(string);
			for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
				if (entry.getValue().toString().indexOf("{") != -1 && 
						entry.getValue().toString().indexOf("}") != -1) {
					try {
						if (entry.getValue().toString().indexOf("date") != -1 &&
								JSONObject.fromObject(entry.getValue()).get("$date") != null) {
							jsonMap.put(entry.getKey(), DateUtil.dateTimeFormat.format(new Date(JSONObject.fromObject(entry.getValue()).getLong("$date"))));
						}
					} catch (Exception e) {
						log.error("mongoDB查询出现其他数据格式~~~~~~" + e);
					}
				}
			}
			values.add(JSONObject.fromObject(jsonMap).toString());
		}
		mongoClient.close();
		return values;
	}
	
	public static void main(String[] args) {
		MongoClient mongoClient = new MongoClient("192.168.13.32", 2890);
		MongoDatabase mongoDataBase = mongoClient.getDatabase("uatdb");
		MongoCollection<Document> collection = mongoDataBase.getCollection("sellerPassportHospitalSellAnalysis");
		
		BasicDBObject cond = new BasicDBObject();
		BasicDBList condList = new BasicDBList();
		BasicDBObject exclude = new BasicDBObject().append("_id", 0);
		Document document = new Document();
		Map<String, Object> searchMap = new HashMap<>();
		searchMap.put("time","2");
		searchMap.put("passportId","110001877");
		searchMap.put("sellerId","user1101869");
		if (searchMap != null) {
			for (Map.Entry<String, Object> entry : searchMap.entrySet()) {
				condList.add(new BasicDBObject(entry.getKey(), entry.getValue()));
			}
		}
		cond.put("$and", condList);
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		sorts.put("maketRatio",1);
		if (sorts != null) {
			for (Map.Entry<String, Integer> entry : sorts.entrySet()) {
				document.append(entry.getKey(), entry.getValue());
			}
		}
		FindIterable<Document> findIterable = null;
		findIterable = collection.find(cond).projection(exclude).sort(document);
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		List<String> list = new ArrayList<>();
		while (mongoCursor.hasNext()) {
			list.add(mongoCursor.next().toJson());
		}
		List<String> values = new ArrayList<>();
		for (String string : list) {
			@SuppressWarnings("unchecked")
			Map<String, Object> jsonMap = (Map<String, Object>) JSON.parse(string);
			for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
				if (entry.getValue().toString().indexOf("{") != -1 && 
						entry.getValue().toString().indexOf("}") != -1) {
					try {
						if (entry.getValue().toString().indexOf("date") != -1 &&
								JSONObject.fromObject(entry.getValue()).get("$date") != null) {
							jsonMap.put(entry.getKey(), DateUtil.dateTimeFormat.format(new Date(JSONObject.fromObject(entry.getValue()).getLong("$date"))));
						}
					} catch (Exception e) {
						log.error("mongoDB查询出现其他数据格式~~~~~~" + e);
					}
				}
			}
			values.add(JSONObject.fromObject(jsonMap).toString());
		}
		mongoClient.close();
		for (String string : values) {
			System.out.println(string);
		}
	}
}
